﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Xml;

namespace OmixJsonServer.Helpers
{
    public static class SerializationHelper
    {
        public static T LoadFromXml<T>(string xml) where T : class
        {
            return (T)LoadFromXML(typeof(T), xml);
        }

        public static string SaveToXML(object myObj)
        {
            DataContractSerializer mySerializer = new DataContractSerializer(myObj.GetType());
            using (StringWriter stringWriter = new StringWriter())
            using (XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter))
            {
                xmltextWriter.Formatting = Formatting.Indented;
                mySerializer.WriteObject(xmltextWriter, myObj);
                return stringWriter.ToString();
            }

        }

        public static object LoadFromXML(object myObj, string XML)
        {
            return LoadFromXML(myObj.GetType(), XML);
        }

        public static object LoadFromXML(Type type, string XML)
        {
            DataContractSerializer mySerializer = new DataContractSerializer(type);
            XmlTextReader reader = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(XML)));
            return mySerializer.ReadObject(reader);
        }

        public static string SaveToJson(object myObj)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            string ret = ser.Serialize(myObj);
            return ret;
        }

        public static object LoadFromJson(Type type, string json)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Deserialize(json, type);
        }

        public static T LoadFromJson<T>(string Json) where T : class
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Deserialize<T>(Json);
        }

        public static object LoadFromJson(object myObj, string json)
        {
            return LoadFromJson(myObj.GetType(), json);
        }


    }
}
